//
//  ViewController.m
//  YingYan
//
//  Created by 吴高烽 on 16/9/25.
//  Copyright © 2016年 吴高烽. All rights reserved.
//

#import "ViewController.h"
#import <BaiduTraceSDK/BaiduTraceSDK-Swift.h>
#import <WebKit/WebKit.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import "Oreder.h"
#import "SVProgressHUD.h"
#import "PrinterSDK.h"
#import "JPUSHService.h"
#import <CoreLocation/CoreLocation.h>
#define serviceID 124980
#define  AK @"AYYuV4ALwYH9SNAtnoW0Q5z7ube9ZbXD"
#define MCODE @"com.estarservice.dmsonline"
@interface ViewController ()<ApplicationServiceDelegate, ApplicationEntityDelegate, ApplicationTrackDelegate,WKScriptMessageHandler, CBCentralManagerDelegate,ApplicationFenceDelegate,WKUIDelegate,WKNavigationDelegate,CLLocationManagerDelegate>
@property (nonatomic ,weak)WKWebView *webView;
@property (nonatomic ,strong)Oreder *oreder;
@property(strong,nonatomic)CBCentralManager* CM;
@property (nonatomic ,assign)BOOL isOpen;
@property (nonatomic ,strong)NSArray  *printList;
@property (nonatomic ,copy)NSString *userid;
@property (nonatomic,strong) CLLocationManager *locationManager;

@end

@implementation ViewController
dispatch_queue_t global_queue;

static bool isStartPressed = TRUE;
static NSString * entityName = @"gaofeng";
static BTRACE * traceInstance = NULL;
bool firstTimeIntoForeGround = true;


- (void)viewDidLoad {
    [super viewDidLoad];
    global_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    [self addObservers];
    [self setupWebView];

}
-(void)setupWebView{
    self.view.backgroundColor = [UIColor whiteColor];
    WKWebViewConfiguration *config = [WKWebViewConfiguration new];
    //初始化偏好设置属性：preferences
    config.preferences = [WKPreferences new];
    //The minimum font size in points default is 0;
    config.preferences.minimumFontSize = 10;
    //是否支持JavaScript
    config.preferences.javaScriptEnabled = YES;
    //不通过用户交互，是否可以打开窗口
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    //通过JS与webView内容交互
    config.userContentController = [WKUserContentController new];
    // 注入JS对象名称senderModel，当JS通过senderModel来调用时，我们可以在WKScriptMessageHandler代理中接收到
    [config.userContentController addScriptMessageHandler:self name:@"senderModel"];
    [config.userContentController addScriptMessageHandler:self name:@"senderStart"];
    [config.userContentController addScriptMessageHandler:self name:@"senderStop"];
    [config.userContentController addScriptMessageHandler:self name:@"print"];
    //    设置webView 的frame
    CGRect frame = CGRectMake(0, 20,[UIScreen mainScreen].bounds.size.width , [UIScreen mainScreen].bounds.size.height-20);
    WKWebView *webView = [[WKWebView alloc]initWithFrame: frame configuration:config];
    webView.UIDelegate = self ;
    webView.navigationDelegate = self ;
    self.webView = webView;
    NSURL *url = [NSURL URLWithString:@"http://www.estarservice.com/DMS/"];
    NSURLRequest *request =[NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
    [self.view addSubview:webView];
    [self startLocation];
}

-(void)viewWillAppear:(BOOL)animated {
    NSLog(@"first viewWillAppear");
    [super viewWillAppear:animated];
    [self doWork];
}
#pragma mark - Trace服务相关的回调方法

- (void)addObservers {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive) name:UIApplicationWillResignActiveNotification object:nil]; //监听是否触发home键挂起程序.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil]; //监听是否重新进入程序.
}

- (void)removeObservers {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}
-(void)applicationWillResignActive {
    NSLog(@"程序即将进入后台执行");
   
}

-(void)applicationDidBecomeActive {
    NSLog(@"程序已经进入前台执行");
    if (firstTimeIntoForeGround) {
        firstTimeIntoForeGround = false;
        return;
    }
    [self doWork];
}
-(void)doWork{
    if (self.userid.length <=1) {
        return;
    }
    [self.webView reload];
    //不妨以IDFV作为entityName,开发者可以使用自己业务相关的唯一标识作为entityName
    //    entityName = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    //使用鹰眼SDK，必须先实例化Trace对象 operationMode 2代表进行长连接，且采集轨迹数据
    traceInstance = [[BTRACE alloc] initWithAk: AK mcode: MCODE serviceId: serviceID entityName: self.userid operationMode: 2];
    
}
- (IBAction)startTrace:(id)sender {
    isStartPressed = TRUE;
    BOOL intervalSetRet = [traceInstance setInterval:10 packInterval:50];
    NSLog(@"设置间隔结果%@",intervalSetRet ? @"YES" : @"NO");
    dispatch_async(global_queue, ^{
        [[BTRACEAction shared] startTrace:self trace:traceInstance];
    });
}

- (IBAction)stopTrace:(id)sender {
    dispatch_async(global_queue, ^{
        [[BTRACEAction shared] stopTrace:self trace:traceInstance];
    });
}

- (void)onStartTrace:(NSInteger)errNo errMsg:(NSString *)errMsg {
    NSLog(@"startTrace: %@", errMsg);
//    NSString* no = [NSString stringWithFormat:@"%ld",(long)errNo];
//    [self putMessageInTextView:no];
//    [self putMessageInTextView:errMsg];
}

- (void)onStopTrace:(NSInteger)errNo errMsg:(NSString *)errMsg {
    NSLog(@"stopTrace: %@", errMsg);
//    [self putMessageInTextView:errMsg];
}

- (void)onPushTrace:(uint8_t)msgType msgContent:(NSString *)msgContent {
    NSLog(@"收到推送消息: 类型[%d] 内容[%@]", msgType, msgContent);
//    [self putMessageInTextView:msgContent];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark- Location and Delegate
- (void)startLocation
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    /** 由于IOS8中定位的授权机制改变 需要进行手动授权
     * 获取授权认证，两个方法：
     * [self.locationManager requestWhenInUseAuthorization];
     * [self.locationManager requestAlwaysAuthorization];
     */
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        NSLog(@"requestWhenInUseAuthorization");
        //        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager requestAlwaysAuthorization];
    }
    
    
    //开始定位，不断调用其代理方法
    [self.locationManager startUpdatingLocation];
    NSLog(@"start gps");
}
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
{
    // 1.获取用户位置的对象
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coordinate = location.coordinate;
    NSLog(@"纬度:%f 经度:%f", coordinate.latitude, coordinate.longitude);
//    
//    self.longitute = [NSNumber numberWithDouble:coordinate.longitude];
//    self.latitude = [NSNumber numberWithDouble:coordinate.latitude];
//    
    // 2.停止定位
    [manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error
{
    if (error.code == kCLErrorDenied) {
        // 提示用户出错原因，可按住Option键点击 KCLErrorDenied的查看更多出错信息，可打印error.code值查找原因所在
    }
}
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"senderModel"]) {
        NSLog(@"111-%@", message.body);
        NSString *alias = message.body ;
        [JPUSHService setAlias:alias callbackSelector:@selector(jpushResult) object:nil];
    }else if([message.name isEqualToString:@"senderStart"]){
        NSString *userid = message.body ;
        [self startWork:userid];
    }else if([message.name isEqualToString:@"senderStop"]){
        NSString *userid = message.body ;
        [self stopWork:userid];
    }else if ([message.name isEqualToString:@"print"]){
//                        NSLog(@"json==%@",message.body);
        Oreder *oreder = [Oreder mj_objectWithKeyValues:message.body];
        self.oreder = oreder ;
        [self checkPrintState];
        
    }
}
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"%s", __FUNCTION__);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
    NSLog(@"%@", message);
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
    NSLog(@"%s", __FUNCTION__);
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm" message:@"JS调用confirm" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
    
    NSLog(@"%@", message);
}
-(void)jpushResult{
    NSLog(@"用户注册成功");
}
-(void)startWork:(NSString*)userID{
    self.userid = userID ;
    traceInstance = [[BTRACE alloc] initWithAk:AK mcode:MCODE serviceId:serviceID entityName: userID operationMode: 2];
    //    traceInstance
    //setInterval代表采集周期，packInterval代表打包上传周期
    BOOL intervalSetRet = [traceInstance setInterval:10 packInterval:50];
    NSLog(@"设置间隔结果%@",intervalSetRet ? @"YES" : @"NO");
    if (intervalSetRet) {
        dispatch_async(global_queue, ^{
            [[BTRACEAction shared] startTrace:self trace:traceInstance];
        });
    }else{
        [SVProgressHUD showErrorWithStatus:@"打卡失败，请重新登录"];
    }
}
-(void)stopWork:(NSString *)userID{
    //结束轨迹追踪，异步执行
    dispatch_async(global_queue, ^{
        if (traceInstance==nil || traceInstance == NULL) {
            traceInstance = [[BTRACE alloc] initWithAk:AK mcode:MCODE serviceId:serviceID entityName: userID operationMode: 2];
        }
        [[BTRACEAction shared] stopTrace:self trace:traceInstance];
        NSLog(@"结束轨迹跟踪");
    });
}
#pragma mark - PrinterDelegate
-(void)checkPrintState{
    if (self.isOpen == NO) {
        self.CM = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
        //        mytimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(timeout) userInfo:nil repeats:NO];
        return ;
    }
    BOOL connected =  [PrinterWraper isPrinterConnected];
    if (connected == NO) {
        if(self.printList.count==0){
            [PrinterWraper StartScanTimeout:5];}else{
                [self showPrintLis];
            }
        return ;
    }
    BOOL available = [PrinterWraper isPrinterAvailable];
    if (available == NO) {
        [SVProgressHUD showErrorWithStatus:@"打印机不可用，请重试"];
        [self showPrintLis];
    }
    [self print: self.oreder];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    NSString *message = nil;
    //    self.isOpen = NO ;
    switch (central.state) {
        case 1:{
            message = @"该设备不支持蓝牙功能,请检查系统设置";
            [self BlueToothOpen:NO];
        }
            break;
        case 2:{
            message = @"该设备蓝牙未授权,请检查系统设置";
            [self BlueToothOpen:NO];
        }
            break;
        case 3:{
            message = @"该设备蓝牙未授权,请检查系统设置";
            [self BlueToothOpen:NO];
        }
            break;
        case 4:{
            message = @"该设备尚未打开蓝牙,请在设置中打开";
            [self BlueToothOpen:NO];
        }
            break;
        case 5:{
            message = @"蓝牙已经成功开启,请稍后再试";
            [self BlueToothOpen:YES];
        }
            break;
        default:
            break;
    }
    if(message!=nil&&message.length!=0)
    {
        NSLog(@"message == %@",message);
    }
}
-(void)showPrintLis{
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"打印机列表" message:@"选择合适的打印机打印" preferredStyle:UIAlertControllerStyleAlert];
    for (CBPeripheral *dic   in self.printList) {
        NSString *name = dic.name ;
        if (name.length<1) {
            name = @"未知设备";
        }
        UIAlertAction *action = [UIAlertAction actionWithTitle:name style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [PrinterWraper connectPrinter:dic.identifier.UUIDString shouldreset:YES];
        }];
        
        [alertC addAction:action];
    }
    if (self.printList.count==0) {
        [SVProgressHUD showErrorWithStatus:@"没有找到可用的打印机"];
        return;
    }
    UIAlertAction *cacel = [UIAlertAction actionWithTitle:@"取消打印" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {    }];
    [alertC addAction:cacel];
    [SVProgressHUD dismiss];
    [self presentViewController:alertC animated:YES completion:nil];
}
-(void)BlueToothOpen:(BOOL)isopen{
    NSLog(@"blueToot = %d",isopen);
    self.isOpen = isopen;
    if (isopen) {
        self.printList=nil;
        [SVProgressHUD showSuccessWithStatus:@"蓝牙打开成功"];
        [PrinterWraper SetBlutoothDelegate:self];
        [PrinterWraper StartScanTimeout:10];
    }else{
        [PrinterWraper StopScan];
        [SVProgressHUD showWithStatus:@"请检查手机蓝牙功能"];
    }
}
-(void)updateBluetoothDevice:(NSMutableArray*)devices{
    NSLog(@"devices = %@",devices);
    self.printList = devices ;
}
-(void)didConnected:(NSString*)deviceUid Result:(BOOL)success{
    NSLog(@"deviceUid = %@,success = %d",deviceUid,success);
    if (success) {
        [SVProgressHUD showSuccessWithStatus:@"打印机连接成功"];
                [self print:self.oreder];
    }
}
-(void)finishPrint{
    
}
-(void)print:(Oreder*)order{
    
    [PrinterWraper setPrintFormat:1 LineSpace:14 alinment:1 rotation:0];
    [PrinterWraper addPrintText:[NSString stringWithFormat:@"%@\n",order.COMPANY_NAME]];
    [PrinterWraper setPrintFormat:3 LineSpace:1 alinment:1 rotation:0];
    [PrinterWraper addPrintText:[NSString stringWithFormat:@"%@\n",order.ORDER_TYPE]];
    [PrinterWraper setPrintFormat:1 LineSpace:1 alinment:0 rotation:0];
    [PrinterWraper addPrintText:[NSString stringWithFormat:@"客户:%@\n",order.CUSTOMER_NAME]];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSDate *date = [NSDate date];
    NSString *time = [formatter stringFromDate:date];
    /*"SALES_DATE":"2016-09-30",
     "SALES_CODE":"S201609300000018",
     "SALES_BY":"丁力",*/
    [PrinterWraper addPrintText:[NSString stringWithFormat:@"日期:%@\n",order.SALES_DATE]];
    [PrinterWraper addPrintText:[NSString stringWithFormat:@"单号:%@\n",order.SALES_CODE]];
    [PrinterWraper addPrintText:[NSString stringWithFormat:@"负责人:%@\n",order.SALES_BY]];
    [PrinterWraper addPrintText:@"-------------------------------\n"];
    [PrinterWraper setPrintFormat:1 LineSpace:1 alinment:0 rotation:0];
    NSMutableArray *mBody = [NSMutableArray array];
    NSArray *headers =@[order.TITLE1,order.TITLE2,order.TITLE3];
    [mBody addObject:headers];
    for (OrderDetail *detail in order.ORDER_DETAIL) {
        NSArray *values0=@[detail.PRODUCT_NAME,@"",@""];
        NSArray *values1 =@[detail.PRICE,detail.QUANTITY,detail.AMOUNT];
        [mBody addObject:values0];
        [mBody addObject:values1];
    }
    [PrinterWraper addItemLines:mBody];
    [PrinterWraper setPrintFormat:1 LineSpace:1 alinment:0 rotation:0];
    NSString *spaces = [self stringSpaceOfCount:5];//字符长度为5的3倍
    [PrinterWraper addPrintText:[NSString stringWithFormat:@"%@%@%@\n",spaces,order.ORDER_AMOUNT_DESC,order.ORDER_AMOUNT]];
    [PrinterWraper addPrintText:[NSString stringWithFormat:@"%@%@%@\n",spaces,order.DISCOUNT_AMOUNT_DESC,order.DISCOUNT_AMOUNT]];
    [PrinterWraper addPrintText:[NSString stringWithFormat:@"%@%@%@\n",spaces,order.RECEIVED_AMOUNT_DESC,order.RECEIVED_AMOUNT]];
    [PrinterWraper addPrintText:@"-------------------------------\n\n\n\n"];
    BOOL res= [PrinterWraper startPrint:nil];
}
-(NSString*)stringSpaceOfCount:(NSInteger)count{
    NSMutableString *str = [NSMutableString string];
    for (NSInteger i =0; i<count; i++) {
        [str appendString:@"   "];
    }
    return str ;
}


@end
